//
//  TwoSum.swift
//  LeeCodeKeepingTests
//
//  Created by cui on 2021/11/12.
//

import XCTest

class TwoSum: XCTestCase {

    override func setUpWithError() throws {
        // Put setup code here. This method is called before the invocation of each test method in the class.
    }

    override func tearDownWithError() throws {
        // Put teardown code here. This method is called after the invocation of each test method in the class.
    }

    func testExample() throws {
        // This is an example of a functional test case.
        // Use XCTAssert and related functions to verify your tests produce the correct results.
        let nums = [-1,-2,-3,-4,-5]
        let target = -8
        let array = self.twoSum(nums, target)
        XCTAssertEqual([2,4], array)
    }

    func testPerformanceExample() throws {
        // This is an example of a performance test case.
        self.measure {
            // Put the code you want to measure the time of here.
            let nums = [-1,-2,-3,-4,-5]
            let target = -8
            let array = self.twoSum(nums, target)
            print(array)
        }
    }
    
    func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
        var numArray = nums
        var array = [Int]()
        for num in numArray {
            var lastNum: Int = 0
            
            lastNum = target - num
            if let index = numArray.firstIndex(of: num) {
                numArray.remove(at: index)
            }
            if numArray.contains(lastNum) {
                if let index = nums.firstIndex(of: num) {
                    array.append(index)
                }
            }
            
            if array.count == 1 {
                if lastNum == num {
                    if let index = nums.lastIndex(of: lastNum) {
                        
                        array.append(index)
                        break
                    }
                } else
                {
                    if let index = nums.firstIndex(of: lastNum) {
                        
                        array.append(index)
                        break
                    }
                }
            }
        }
        return array
    }

}
